// 状态
import { getToken, removeToken, setTimeStamp, setToken } from '@/utils/auth'
import { login } from '@/api'
import router from '@/router'
import { getUserDetailById, getUserInfo } from '@/api/user'

const state = {
  token: getToken(),
  // 定义用户信息对象
  userInfo: {}
}
// 修改状态
const mutations = {
//  修改token的方法
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  //  移出token
  removeToken(state) {
    state.token = null

    // 移除本地存储的token cookie
    removeToken()
  },
  // 定义修改用户信息的mutations
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
// 执行异步
const actions = {
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  },
  async login(context, data) {
    // 调用登录的接口
    try {
      const res = await login(data)
      // console.log(res)
      context.commit('setToken', res)
      setTimeStamp()
      router.push('/')
    } catch (e) {
      // console.log(e)
    }
  },
  // 定义获取用户信息的actions
  async getUserInfo(context) {
    try {
      // 两个获取用户信息的头像进行合并
      const res = await getUserInfo()
      const baseUserInfo = await getUserDetailById(res.userId)
      // console.log(baseUserInfo)
      context.commit('setUserInfo', {
        ...res,
        ...baseUserInfo
      })
    } catch (e) {
      // console.log(e)
    }
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
